const OrganizationModel = require("../model/organization");
const BaseController = require("./base/base");
const Result = require("../utils/result");
class OrgController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 获取社团列表
  findOrgList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize = 5, page = 1, org_name = '', org_president = '' } = req.query;
        pagesize *= 1
        page *= 1
        // 页码对应的数据查询开始位置
        let start = (page - 1) * pagesize;
        // 将用户信息从数据库中查询出来
        const _filter = { org_name: { $regex: org_name, $options: 'i' }, org_president: { $regex: org_president, $options: 'i' } }
        let list = await OrganizationModel.find(_filter).limit(pagesize).skip(start)
        let total = await OrganizationModel.countDocuments(_filter)
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加社团
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { org_num = '', org_name = '', org_president = '', org_state = 1, setup_time } = req.body;
        org_state *= 1
        if (!org_name) return res.json(Result.fail("社团名不能为空"));
        let ret = await OrganizationModel.findOne({ org_name });
        if (ret) return res.json(Result.fail("社团名已存在"));
        // let numret = await OrganizationModel.findOne({ org_num });
        // if (numret) return res.json(Result.fail("社团编号已存在"));
        ret = await OrganizationModel.create({ org_num, org_name, org_president, org_state, setup_time });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改社团信息
  updateNotice(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await OrganizationModel.updateOne({ _id: id }, req.body);
        res.json(!ret.matchedCount ? Result.fail("修改失败", ret) : Result.ok("修改成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除社团
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await OrganizationModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new OrgController().resolve();